package com.mazaiting.rabbitmq.listeners;

import cn.hutool.core.collection.CollectionUtil;
import com.mazaiting.common.core.ex.exceptions.BaseException;
import com.mazaiting.rabbitmq.config.RabbitModuleProperties;
import com.mazaiting.rabbitmq.domain.info.RabbitModuleInfo;
import com.mazaiting.rabbitmq.service.IDynamicMQService;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 自动注册 MQ 监听
 * 如果不想执行次自动注册, 则在配置文件中不配置即可
 * @author mazaiting
 * @create_time 2022/9/29 00:01
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AutoRegisterMQListener implements ApplicationListener<ContextRefreshedEvent> {

    /**
     * 动态 MQ 服务
     */
    private final IDynamicMQService dynamicMQService;

    private final RabbitModuleProperties rabbitModuleProperties;

    /**
     * 此处只做 MQ 的自动添加, 如果需要设置公共的监听可调用startListener()方法
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(@NonNull ContextRefreshedEvent event) {
        log.info("==========  自动注册 MQ 开始  ==========");
        try {
            // 获取模块信息
            List<RabbitModuleInfo> modules = rabbitModuleProperties.getModules();
            // 如果不为空则注册
            if (CollectionUtil.isNotEmpty(modules)) {
                for (RabbitModuleInfo moduleInfo : modules) {
                    dynamicMQService.add(moduleInfo);
//                    dynamicMQService.startListener(moduleInfo, 5, new IMessageCallback<Object>() {
//                        @Override
//                        public void handleMessage(Message message, Channel channel, Object data) throws Exception {
//                            log.error("data");
//                        }
//                    });
                }
            }
        } catch (BaseException e) {
            log.error("注册 MQ 失败: " + e.getMessage());
        }
        log.info("==========  自动注册 MQ 结束  ==========");
    }
}
